package org.example.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.example.aop.Valid;
import org.example.util.JWTUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Aspect
@Component
public class ValidAspect {

    @Resource
    private JWTUtil jwtUtil;

    @Pointcut("@annotation(org.example.aop.Valid)")
    public void validMethod() {}

    // 在方法执行前执行 token 校验
    @Before("validMethod()")
    public void validateToken(JoinPoint joinPoint) throws Exception {
        // 获取请求头中的 token
        String token = getRequestToken();

        if (token == null || token.isEmpty()) {
            throw new TokenExpiredException("Token is missing or empty.");
        }

        // 校验 token 是否过期
        if (jwtUtil.getUserIdByToken(token) == null) {
            throw new TokenExpiredException("Token has expired.");
        }

    }

    // 获取请求头中的 token
    private String getRequestToken() {
        // 获取当前请求的 HttpServletRequest 对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 从请求头中获取 Authorization 字段
            return request.getHeader(HttpHeaders.AUTHORIZATION);
        }

        return null; // 如果 RequestContextHolder 没有有效的请求上下文，返回 null
    }


    // 自定义异常类，用于抛出 token 过期的异常
    public static class TokenExpiredException extends Exception {
        public TokenExpiredException(String message) {
            super(message);
        }
    }
}